package com.woniuxy.predicate;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * @Author: 马宇航
 * @Description: TODO
 * @DateTime: 22/12/08/0008 16:26
 * @Component: 成都蜗牛学苑
 **/
@Component
public class PidlimitRoutePredicateFactory extends AbstractRoutePredicateFactory<PidlimitRoutePredicateFactory.Config> {
    public PidlimitRoutePredicateFactory() {
        //确保抛出的是PidlimitRoutePredicateFactory里面的Config的class对象
        super(Config.class);
    }
    /**
     * - Pidlimit=1,3  需要截取1赋值给minPid，3赋值给maxPid
     * ChangeLog : 1. 创建 (22/12/08/0008 16:44 [马宇航]);
     *
     * @return java.util.List<java.lang.String>
    */
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("minPid","maxPid");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                String path = serverWebExchange.getRequest().getURI().getPath();
                String[] split = path.split("/");
                String pidString = split[split.length - 1];
                int pid = Integer.parseInt(pidString);
                if(config.getMinPid()<=pid&&pid<=config.getMaxPid()){
                    return true;
                }else {
                    return false;
                }
            }
        };
    }

    /**
    * @Author: 马宇航
    * @Todo: 静态内部类：它和 写外面是一样的！
    * @DateTime:  22/12/08/0008 16:28
    * @Component: 成都蜗牛学苑
    **/
    public static class Config{
        int minPid;
        int maxPid;

        public int getMinPid() {
            return minPid;
        }

        public void setMinPid(int minPid) {
            this.minPid = minPid;
        }

        public int getMaxPid() {
            return maxPid;
        }

        public void setMaxPid(int maxPid) {
            this.maxPid = maxPid;
        }
    }
}
